package com.itheima.service.impl;

import com.alibaba.dubbo.config.annotation.Reference;
import com.alibaba.dubbo.config.annotation.Service;
import com.alibaba.fastjson.JSON;
import com.itheima.dao.MenuDao;
import com.itheima.dao.UserDao;
import com.itheima.pojo.Menu;
import com.itheima.pojo.Role;
import com.itheima.pojo.User;
import com.itheima.service.MenuService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import redis.clients.jedis.JedisPool;

import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

@Service(interfaceClass = MenuService.class)
@Transactional
public class MenuServiceImpl implements MenuService {

    @Autowired
    private MenuDao menuDao;
    @Autowired
    private UserDao userDao;
    @Autowired
    private JedisPool jedisPool;

    @Override
    public List<Menu> findAll() {
        List<Menu> list = menuDao.findAll();
        return list;
    }

    @Override
    public List<Menu> findByUser(String username) {
        User user = userDao.findByUsername(username);
        Set<Integer> menuIds = new HashSet<>();
        List<Menu> list = new ArrayList<>();
        Integer id = user.getId();
        List<Integer> roleIds = userDao.findRoleIdsByUserId(id);
        for (Integer roleId : roleIds) {
            menuIds = menuDao.findMenuIds(roleId);
        }
        for (Integer menuId : menuIds) {
            Menu menu = menuDao.findById(menuId);
            Integer level = menuDao.findLevelById(menuId);
            if (level == 1) {
                list.add(menu);
                List<Menu> menus = menuDao.findSonMenu(menuId);
                menu.setChildren(menus);
            }
        }
        String json = JSON.toJSON(list).toString();
        jedisPool.getResource().setex(username,60*60*24*30,json);
        return list;
//        for (Menu menu : list) {
//            List<Menu> menuChildren = menu.getChildren();
//
//
//            jedisPool.getResource().lpush("parentlist",menu.getName());
//
//            for (Menu menuChild : menuChildren) {
//                jedisPool.getResource().lpush("childrenlist",menuChild.getName());
//                String a ="o";
//                String s = JSON.toJSONString(a);
//            }
//        }
    }


}
